<?php

/**
 * Maikuro Framework
 *
 * LICENSE:
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * The license is bundled with this package in the file LICENSE.txt.
 * You may also obtain a copy of the License at this URL:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @copyright  Copyright (c) 2010, Jonathan Hedrén
 * @author     Jonathan Hedrén <jonathan.hedren@gmail.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 */

/**
 * A "flash" messenger class. Stores messages in the session.
 */
class Messenger
{
    const INFO = 'INFO';
    const WARNING = 'WARNING';
    const ERROR = 'ERROR';

    /**
     * @var array
     */
    protected $messages = array();

    /**
     * Adds a message with an optional $type.
     *
     * @param string $message
     * @param string $type
     * @return Messenger
     */
    public function addMessage($message, $type = self::INFO)
    {
        if (!isset($this->messages[$type])) {
            $this->messages[$type] = array();
        }
        $this->messages[$type] = $message;
        return $this;
    }

    /**
     * Clears (removes) messages. If a $type is specified,
     * only messages of type $type will be cleared. Else all
     * messages will be cleared.
     *
     * @param string $type
     * @return Messenger
     */
    public function clearMessages($type = null)
    {
        if ($type != null && isset($this->messages[$type])) {
            unset($this->messages[$type]);
            return $this;
        }
        $this->messages = array();
        return $this;
    }

	/**
	 * Gets all messages. If a $type is specified,
	 * only messages of type $type will be returned.
	 * Messages are cleared (i.e. removed) after they're fetched.
	 *
	 * @param $type
	 * @return array
	 */
	public function getMessages($type = null, $clearMessages = true)
	{
		$messages = array();
		if ($type !== null && isset($this->messages[$type])) {
            $messages = $this->messages[$type];
		} else {
			$messages = $this->messages;
		}
        if ($clearMessages) {
            $this->clearMessages($type);
        }
		return $messages;
	}

    /**
     * Checks if the Messenger has any messages. 
     *
     * @param string $type
     * @return boolean
     */
	public function hasMessages($type = null)
	{
		if ($type != null) {
            if (isset($this->messages[$type])) {
                return true;
            }
			return false;
		}
		return (boolean) count($this->messages);
	}
}